<template>
  <div class="wrapper" :style="{width: hasNavTree ? 'calc(100% - 220px)' : ''}" ref="datagrid">
    <div class="tool">
      <datagrid-search ref="datagridSearch" :isPicker="isPicker" :gridField="gridField" :gridFieldSub="gridFieldSub" :gridSearch.sync="gridSearch" @search="search"></datagrid-search>
      <datagrid-tool :tapImport="tapImport" :isPicker="isPicker" :gridTool="gridTool" :gridDo="gridDo" @tapTool="tapTool" @tapAdd="tapAdd" @tapSetting="tapSetting" @tapDelMulti="tapDelMulti" @tapCopy="tapCopy" @startBorder="startBorder" @overBorder="overBorder"></datagrid-tool>
    </div>
    <datagrid-table :isMultiplePicker="isMultiplePicker" :isPicker="isPicker" :isTabPane="isTabPane" @dbclickRow="dbclickRow" @reloadPage="reloadPage" ref="dataTable" @changeSort="changeSort" @tapEdit="tapEdit"  @tapDel="tapDel" :rowClass="rowClass" @tapCustBtn="tapCustBtn" @tapCustButton="tapCustButton" :gridField="tableField" :custButton="custButton" :gridName="gridName" :gridData="list" :gridDo="gridDo" :controller="controller" ></datagrid-table>
    <datagrid-page :isPicker="isPicker" :currentPageSize="currentPageSize" @tapPage="tapPage" @tapPageSize="tapPageSize" :currentPage="currentPage" :pageSizeOption="pageSizeOption" :total="total"></datagrid-page>
    <div class="datagrid-picker-tool" v-if="isPicker">
      <el-button @click="tapPickerClose">取 消</el-button>
      <el-button type="primary" @click="tapPickerGet">取 用</el-button>
    </div>
    <dialog-form ref="addForm" formTypeProp="add" :formSize="formSize" :formWidth="formWidth" :formData="addForm" :formSubData="addSubForm"   @submitSuccess="addSuccess" :controller="controller" :resource="resource"></dialog-form>
    <dialog-form ref="editForm" formTypeProp="edit" :formSize="formSize" :formWidth="formWidth" :formData="editForm" :formSubData="editSubForm"  @submitSuccess="editSuccess" :controller="controller" :resource="resource"></dialog-form>
    <datagrid-setting ref="datagridSetting" :gridField="tableField" :controller="controller" :gridName="gridName" @saveTableShowField="saveTableShowField"></datagrid-setting>
    <template v-for="item in custForm">
      <dialog-form :key="item.button" ref="custForm" :formSize="item.formSize" :formTitle="item.formTitle" :formTypeProp="item.custType == 'form' ? 'edit' : 'look'" :width="item.formWidth" :formData="item.editForm" :formSubData="item.editFormSub"  @submitSuccess="custOperateSuccess" :getEditActionProp="item.getEditActionProp" :editActionProp="item.editActionProp" :resource="resource"></dialog-form>
    </template>
    <el-dialog :title="dialogQrcode.title" :visible.sync="dialogQrcode.isShow">
      <div class="dialog-qrcode-wrapper">
        <div class="dialog-qrcode" ref="dialogQrcode"></div>
        <div class="dialog-qrcode-url">{{dialogQrcode.url}}</div>
      </div>
    </el-dialog>
    <importEditor ref="importEditor" @submit="submitImport"  :gridDo="gridDo"></importEditor>

  </div>

</template>
<style scoped>
  .wrapper{width:100%;}
  .dialog-qrcode{display: flex;align-items: center;justify-content: center;}
  .dialog-qrcode-url{text-align: center;padding-top:20px;}
  .datagrid-picker-tool{display: flex;justify-content: flex-end;padding-top:20px;}
</style>
<script>
import DatagridSearch from './datagridSearch';
import DatagridTool from './datagridTool';
import DatagridTable from './datagridTable';
import DatagridPage from './datagridPage';
import DialogForm from '@/components/common/dialogForm';
import DatagridSetting from './datagridSetting';
import importEditor from 'common/importEditor';

import { getPage,getEdit,delData,delDataMulti,delSure} from '@/api/common';
import { isString,isArray } from '@/utils';

import QRCode from 'qrcodejs2';

export default {
  components:{
    DatagridSearch,
    DatagridTool,
    DatagridTable,
    DatagridPage,
    DatagridSetting,
    DialogForm,
    importEditor
  },
  props:{
    navTree:{
      type:Object,
      default(){
        return {}
      }
    },
    isTabPane:{
      type:Boolean,
      default(){
        return false;
      }
    },
    isPicker:{
      type:Boolean,
      default(){
        return false;
      }
    },
    isMultiplePicker:{
      type:Boolean,
      default(){
        return false;
      }
    },
    customize:{
      type:Array,
      default(){
        return [];
      }
    },
    controller:{
      type:String,
      default(){
        return '';
      }
    },
    resource:{
      type:String,
      default(){
        return 'id';
      }
    },
    getPageAction:{
      type:String,
      default(){
        return '';
      }
    },
    formSize:{
      type:String,
      default(){
        return '';
      }
    },
    //表格名称，匹配用户设置
    gridName:{
      type:String,
      default(){
        return '';
      }
    },
    /*表格主部属性 */
    gridField:{
      type:Array,
      default(){
        return []
      }
    },
    /*表格子部属性 */
    gridFieldSub:{
      type:Array,
      default(){
        return []
      }
    },
    gridData:{
      type:Array,
      default(){
        return []
      }
    },
    gridDo:{
      type:Object,
      default(){
        return {};
      }
    },
    gridTool:{
      type:Array,
      default(){
       return []
      }
    },
    rowClass:{
      type:String,
      default(){
        return '';
      }
    },
    /*分页属性*/
    pageSizeOption:{
      type:Array,
      default:function(){
        return  [20, 40, 60, 100,500,1000]
      }
    },
    currentPageSize:{
      type:Number,
      default(){
        return 20
      }
    },
    currentPage:{
      type:Number,
      default(){
        return 1
      }
    }
  },
  data(){
    return {
      gridSearch:[],
      searchField:[],
      addForm:{},
      addSubForm:[],
      editForm:{},
      editSubForm:[],
      searchForm:{},
      searchSubForm:[],
      list:[],
      total:0,
      formWidth:'',
      pageSize:20,
      page:1,
      searchData:[],
      sortData:[],//排序
      tableField:[],
      custForm:[],
      custButton:[],
      query:{},
      dialogQrcode:{
        qrcode:null,
        isShow:false,
        dialogQrcodeTitle:'二维码查看'
      },
    }
      
  },
  mounted(){
       //因为用到了ref
    this.getPage();
  },
  created(){
    this.customize.forEach(item=>{
      this.custButton.push(item);
      if (item.custType == 'form' || item.custType == 'look'){
        this.custForm.push(this.initForm(item));
      }
    })
    if (this.formSize == 'small') {
      this.formWidth = '500px';
    } else if (this.formSize == 'big'){
      this.formWidth = '1280px';
    } else {
      this.formWidth = '960px';
    }
    this.gridField.forEach(item => {
      /*
      //处理搜索栏
      if (item.isSearch) {
        this.searchField.push({label:item.label,value:item.field});
        if ( item.isSearchDefault) {
          item.fieldValue = item.field ;
          this.gridSearch.push(item);
        }
      }*/
      //处理新增窗口
      if (item.isAdd) {
        this.addForm[item.field] = {...item};
        if (this.addForm[item.field].type == 'pics') {
          this.addForm[item.field].value = [];
        } else {
          this.addForm[item.field].value = '';
        }
        if (this.addForm[item.field].addReadonly) {
          this.addForm[item.field].readonly = true;
        }
      }
      if (item.isEdit) {
        this.editForm[item.field] = {...item};
        if (this.editForm[item.field].type == 'pics') {
          this.editForm[item.field].value = [];
        } else {
          this.editForm[item.field].value = '';
        }
        if (this.editForm[item.field].editReadonly) {
          this.editForm[item.field].readonly = true;
        }
      }
      if (item.isSearch){
        if (item.type != 'pics' && item.type != 'richtext') this.searchForm[item.field] = {...item};
      }
    });

    this.gridFieldSub.forEach((group,groupIndex) => {
      let addSubForm = {};
      let editSubForm = {};
      let searchSubForm = {};
      group.fields.forEach(item=>{
        /*
        //处理搜索栏
        if (item.isSearch) {
          this.searchField.push({label:item.label,value:item.field});
          if ( item.isSearchDefault) {
            item.fieldValue = item.field ;
            this.gridSearch.push(item);
          }
        }*/
        //处理新增窗口
        if (item.isAdd) {
          
          addSubForm[item.field] = {...item};
          if (addSubForm[item.field].type == 'pics') {
            addSubForm[item.field].value = [];
          } else {
            addSubForm[item.field].value = '';
          }
          if (addSubForm[item.field].addReadonly) {
            addSubForm[item.field].readonly = true;
          }
        }
        if (item.isEdit) {
          editSubForm[item.field] = {...item};
          if (editSubForm[item.field].type == 'pics') {
            editSubForm[item.field].value = [];
          } else {
            editSubForm[item.field].value = '';
          }
          if (editSubForm[item.field].editReadonly) {
            editSubForm[item.field].readonly = true;
          }
        }
        if (item.isSearch){
          if (item.type != 'pics' && item.type != 'richtext') searchSubForm[item.field] = {...item};
        }
      });
      this.addSubForm.push({formTitle:group.title,formData:addSubForm});
      this.editSubForm.push({formTitle:group.title,formData:editSubForm});
      this.searchSubForm.push({formTitle:group.title,formData:searchSubForm});
    });
    let tableField = [...this.gridField];
    this.gridFieldSub.forEach(item=>{
      tableField = tableField.concat(item.fields);
    });
    this.tableField = tableField;

  },
  methods:{
    initForm(formParams){
      if (formParams.formSize == 'small') {
        formParams.formWidth = '500px';
      } else {
        formParams.formWidth = '960px';
      }
      if (formParams.gridField) {
        formParams.addForm = {};
        formParams.editForm = {};
        formParams.gridField.forEach(item => {
          /*
          //处理搜索栏
          if (item.isSearch) {
            this.searchField.push({label:item.label,value:item.field});
            if ( item.isSearchDefault) {
              item.fieldValue = item.field ;
              this.gridSearch.push(item);
            }
          }*/
          //处理新增窗口
          if (item.isAdd) {
            formParams.addForm[item.field] = {...item};
            if (formParams.addForm[item.field].type == 'pics') {
              formParams.addForm[item.field].value = [];
            } else {
              formParams.addForm[item.field].value = '';
            }
            if (formParams.addForm[item.field].addReadonly) {
              formParams.addForm[item.field].readonly = true;
            }
          }
          if (item.isEdit) {
            formParams.editForm[item.field] = {...item};
            if (formParams.editForm[item.field].type == 'pics') {
              formParams.editForm[item.field].value = [];
            } else {
              formParams.editForm[item.field].value = '';
            }
            if (formParams.editForm[item.field].editReadonly) {
              formParams.editForm[item.field].readonly = true;
            }
          }
        });
      }
      if (formParams.gridFieldSub) {
        formParams.addSubForm = [];
        formParams.editSubForm = [];
        formParams.gridFieldSub.forEach((group,groupIndex) => {
          let addSubForm = {};
          let editSubForm = {};
          group.fields.forEach(item=>{
            /*
            //处理搜索栏
            if (item.isSearch) {
              this.searchField.push({label:item.label,value:item.field});
              if ( item.isSearchDefault) {
                item.fieldValue = item.field ;
                this.gridSearch.push(item);
              }
            }*/
            //处理新增窗口
            if (item.isAdd) {
              
              addSubForm[item.field] = {...item};
              if (addSubForm[item.field].type == 'pics') {
                addSubForm[item.field].value = [];
              } else {
                addSubForm[item.field].value = '';
              }
              if (addSubForm[item.field].addReadonly) {
                addSubForm[item.field].readonly = true;
              }
            }
            if (item.isEdit) {
              editSubForm[item.field] = {...item};
              if (editSubForm[item.field].type == 'pics') {
                editSubForm[item.field].value = [];
              } else {
                editSubForm[item.field].value = '';
              }
              if (editSubForm[item.field].editReadonly) {
                editSubForm[item.field].readonly = true;
              }
            }
          });
          formParams.addSubForm.push({formTitle:group.title,formData:addSubForm});
          formParams.editSubForm.push({formTitle:group.title,formData:editSubForm});
        });
      }
      let tableField = [];
      if (formParams.gridField) tableField =[...formParams.gridField];
      if (formParams.gridFieldSub) {
          formParams.gridFieldSub.forEach(item=>{
          tableField = tableField.concat(item.fields);
        });
      }
      formParams.tableField = tableField;
      return formParams;
    },
    tapTool(button){
        if (button.custType == 'form' || button.custType == 'look'){
          
        } else if (button.custType == 'link'){
          if (button.linkType == 1){
            let query = {};
            if (button.query){
              button.query.forEach(queryItem=>{
                query[queryItem[0]] = row[queryItem[1]] ? row[queryItem[1]] : '';
                if (queryItem.length == 3) {
                  query[queryItem[0]] = query[queryItem[0]] ? query[queryItem[0]] : queryItem[2]
                }
              });
            }
            this.$router.push({ path: button.linkUrl, query: query})
          }
        } else if (button.custType == 'request') {
          if (button.confirm){
            this.$tool.confirm(button.confirm).then(()=>{
              this.$request({
                c:button.action,
                method:button.requestMethod ? button.requestMethod : 'POST',
                data:button.data,
                errorType:button.errorType,
                loading:button.loading,
              }).then(data=>{
                this.$tool.succToast(data ? data : '操作成功');
                if (button.reload) this.getPage();
              })
            }).catch(()=>{

            })
          }
        }
    },
    tapCustButton(button,row){
      let custFormBtnIndex = 0;
      this.custButton.forEach((item,index)=>{
        if (item.button && item.button == button) {
          if (item.custType == 'form' || item.custType == 'look'){
            if (row[this.resource]) {
              this.$refs.custForm[custFormBtnIndex].openForm(row[this.resource]);
            } else{
              this.$tool.errorToast('未获取到数据标识');
            }
          } else if (item.custType == 'link'){
            if (item.linkType == 1){
              let query = {};
              if (item.query){
                item.query.forEach(queryItem=>{
                  query[queryItem[0]] = row[queryItem[1]] ? row[queryItem[1]] : '';
                  if (queryItem.length == 3) {
                    query[queryItem[0]] = query[queryItem[0]] ? query[queryItem[0]] : queryItem[2]
                  }
                });
              }
              this.$router.push({ path: item.linkUrl, query: query})
            }
          } else if (item.custType == 'dialog'){
            if (item.dialogType == 'qrcode'){
              this.dialogQrcode = {isShow:false};
              let qrcodeUrl = '';
              for (let urlParamKey in item.urlParam) {
                if (isString(item.urlParam[urlParamKey])) {
                  qrcodeUrl += urlParamKey + '=' + row[item.urlParam[urlParamKey]] + '&';
                }
              }
              if (qrcodeUrl) qrcodeUrl = item.qrcodeUrl + '?' + qrcodeUrl.substr(0,qrcodeUrl.length - 1);

              for (let viewParamKey in item.viewParam) {
                if (isString(item.viewParam[viewParamKey])) {
                  this.dialogQrcode[viewParamKey] = row[item.viewParam[viewParamKey]];
                }
              }

              this.dialogQrcode.isShow = true;
              this.dialogQrcode.url = qrcodeUrl;

              this.$nextTick(()=>{
                this.$refs.dialogQrcode.innerHTML = '';
                this.dialogQrcode.qrcode = new QRCode(this.$refs.dialogQrcode, {
                  width: 150,
                  height: 150, // 高度
                  text: qrcodeUrl // 二维码内容
                  //render: 'canvas' // 设置渲染方式（有两种方式 table和canvas，默认是canvas）
                  //background: '#f0f'
                  //foreground: '#ff0'
                })
              })
            }
          }
        }
        if (item.custType == 'form' || item.custType == 'look'){
          custFormBtnIndex++;
        }
      })
    },
    search(){
      /*
      for (let key in this.gridSearch) {
        if (this.gridSearch[key].value){
          this.searchData[this.gridSearch[key].field] = this.gridSearch[key].value;
        }
      }*/
      this.getPage();
    },
    reloadPage(){
      this.getPage();
    },
    //父组件调用
    resetSearch(){
      this.$refs.datagridSearch.resetSearch();
    },
    getPage(){
      let params = {};
      params[this.$system.currentPageField] = this.page;
      params[this.$system.pageSizeField] = this.pageSize;
      for (let key in this.searchData) {
        params[key] = this.searchData[key];
      }
      params['where'] = {};
      this.gridSearch.forEach(item=>{
        let field = item.searchAlias ? item.searchAlias : (item.alias ? item.alias + '.' +item.fieldValue : item.fieldValue);
        if (item.value || item.value == '0' || item.value === false) {
          if (item.type == 'daterange' && item.startField && item.endField) {
            params['where'][item.startField] = item.value[0];
            params['where'][item.endField] = item.value[1];
          } else {
            params['where'][field] = item.value;
          }
        }
      })
      params['orderby'] = {};
      this.sortData.forEach(item=>{
        params['orderby'][item.field] = item.order;
      })
      params.query = {};
      for (let k in this.$route.query) {
        params.query[k] = this.$route.query[k];
      }
      for (let k in this.query) {
        params.query[k] = this.query[k];
      }
      this.$refs.dataTable.showLoading();
      let actionUrl = '';
      if (this.getPageAction){
        actionUrl = this.getPageAction;
      } else {
        if (this.$system.requestApiStyle == 'restful') {
          actionUrl = this.controller + '/page';
        } else {
          actionUrl = this.controller + '/getPage';
        }
      }
      getPage(actionUrl,params).then(data=>{
        if (this.$system.requestApiStyle == 'restful') {
          this.list = data.records;
        } else {
          this.list = data.list;
        }
        this.total = data.total;
        this.$refs.dataTable.hideLoading();
      }).catch(error=>{
        this.$refs.dataTable.hideLoading();
      });
    },
    tapCustBtn(callbackEvent,row){

      this.$emit('tapCustBtn',callbackEvent,row);
    },
    custOperateSuccess(){
      this.getPage();
    },
    addSuccess(){
      this.getPage();
    },
    editSuccess(){
      this.getPage();
    },
    changeSort(params){
      this.sortData = [];
      if (params.length > 0)  {
        params.forEach(item=>{
          this.sortData.push(item);
        })
      }
      this.getPage();
    },
    startBorder(){
      this.$refs.dataTable.setBorderShow(true);
    },
    overBorder(){
      
      //this.$tool.loading('保存中');
      let columns = this.$refs.dataTable.getColumns();
      let tableSetting = this.$store.getters.userSetting.datagridTable;
      if (!tableSetting) tableSetting = {};
      if (!tableSetting[this.gridName]) tableSetting[this.gridName] = {};

      columns.forEach(column=>{
        let index = this.tableField.findIndex(item=>item.field == column.property);
        if (index > -1) {
          if (!tableSetting[this.gridName][column.property]) tableSetting[this.gridName][column.property] = {field:column.property};
          if (column.width) tableSetting[this.gridName][column.property].width = column.width;
          if (column.minWidth) tableSetting[this.gridName][column.property].minWidth = column.minWidth;
        }
      })
      this.$store.dispatch('permission/saveTableShowField',{gridName:this.gridName,data:tableSetting}).then(() => {
        this.$tool.loading();
        this.$tool.succToast('保存成功');
        this.$refs.dataTable.setBorderShow(false);
      })
      
    },
    tapEdit(row){
      this.$refs.editForm.openForm(row[this.resource]);
    },
    tapAdd(){
      this.$refs.addForm.openForm();
    },
    tapDel(row){
      if (this.gridDo.delSure){
        delSure(this.gridDo.delSure).then(data=>{
          this.delData(row[this.resource],data.msg ? data.msg : '');
        });
      } else {
        this.delData(row[this.resource])
      }
    },
    tapCopy(){
      let rows = this.$refs.dataTable.getSelection();
      let count = rows.length;
      if (count <= 0) return this.$tool.toast('请先勾选1条要复制的内容');
      if (count != 1) return this.$tool.toast('复制操作只能勾选1条内容');
      this.$refs.addForm.openForm(rows[0][this.resource]);
    },
    tapDelMulti(msg){
      let rows = this.$refs.dataTable.getSelection();
      let count = rows.length;
      if (count <= 0) return;
      this.$confirm(msg ? msg : '此操作将永久删除'+count+'条数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let ids = [];
          rows.forEach(item=>ids.push(item.id));
          let actionUrl,params = {};
          if (this.$system.requestApiStyle == 'restful') {
            actionUrl = this.delDataAction ? this.delDataAction : this.controller + '';
            if (this.resource) actionUrl += '/'+ids.join(',');
          } else {
            actionUrl = this.delDataMultiAction ? this.delDataMultiAction : this.controller + '/delDataMulti';
            params.data = {ids};
          }
          delDataMulti(actionUrl,params).then(data =>{
            if (data.type == 2){
              this.$tool.succToast(data.num+'条数据删除成功');
            } else if (data.type == 1){
              this.$tool.warnToast('共'+data.total+'条数据，'+data.num+'条删除成功，'+(data.total - data.num)+'条删除失败');
            } else if (data.type == 0){
              this.$tool.errorToast('未成功删除任何数据');
            }
            
            this.getPage();
          });
        }).catch(() => {
          //取消        
        });
    },
    delData(id,msg = ''){
      
      this.$confirm(msg ? msg : '此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let actionUrl,params = {};
          if (this.$system.requestApiStyle == 'restful') {
            actionUrl = this.delDataAction ? this.delDataAction : this.controller + '';
            if (this.resource) actionUrl += '/'+id;
          } else {
            actionUrl = this.delDataAction ? this.delDataAction : this.controller + '/delData';
            params.data = {id};
          }
          delData(actionUrl,params).then(data =>{
            this.$tool.succToast('删除成功');
            this.getPage();
          });
        }).catch(() => {
          //取消        
        });
    },
    closeEditDialog(){
      this.isShowEditDialog = false;
      for (let key in this.editForm){
       if (this.editForm[key].type == 'pics'){
          this.$set( this.editForm[key],'value', []);
        } else {
          this.$set( this.editForm[key],'value', '');
        }
      }
      
    },
    tapPage(page){
      this.page = page;
      this.getPage();
    },
    tapPageSize(pageSize){
      this.pageSize = pageSize;
      this.getPage();
    },
    tapSetting(){
      this.$refs.datagridSetting.openSetting();
    },
    saveTableShowField(){
      this.$refs.dataTable.setTableField();
    },
    setQuery(query){
      this.query = query;
      this.getPage();
    },
    dbclickRow(row, column, cell, e){
      if (this.isPicker && !this.isMultiplePicker) {
        this.$emit('pick',[row]);
      }
    },
    tapPickerClose(){
      this.$emit('close')
    },
    tapPickerGet(){
      let rows;
      if (this.isMultiplePicker) {
        rows = this.$refs.dataTable.getSelection();
      } else {
        let row = this.$refs.dataTable.getCurrentRow();
        rows = [row];
      }
      let count = rows.length;
      if (count <= 0) {
        this.tapPickerClose();
        return;
      };
      this.$emit('pick',rows);
    },
    tapImport(){
      this.$refs.importEditor.open();
    },
    submitImport(list){
      let params = {};
      params.data = list;
      params.query = {};
      for (let k in this.$route.query) {
        params.query[k] = this.$route.query[k];
      }
      for (let k in this.query) {
        params.query[k] = this.query[k];
      }
      this.$request({
        c:this.controller + '/importData',
        data:params,
        loading:'导入中'
      }).then(res=>{
        this.$refs.importEditor.close();
        this.$tool.succToast('成功导入'+res.succNum+'条数据');
        this.reloadPage();
      })
    }
  },
  computed:{
    hasNavTree(){
      return this.navTree.controller ? true : false
    }
  }
}
//本页已经一样
</script>